package com.atguigu.flinkSql;

import com.atguigu.been.WaterSensor;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.ProcessFunction;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;
import org.apache.flink.types.Row;
import org.apache.flink.util.Collector;

import static org.apache.flink.table.api.Expressions.$;

/**
 * @author wky
 * @create 2021-07-21-9:21
 */
public class Flink02_TableApi_Agg_BasicUse {
    public static void main(String[] args) {
        //创建流执行环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);
        DataStreamSource<WaterSensor> streamSource = env.fromElements(new WaterSensor("sensor_1", 1000L, 10),
                new WaterSensor("sensor_1", 2000L, 20),
                new WaterSensor("sensor_2", 3000L, 30),
                new WaterSensor("sensor_1", 4000L, 40),
                new WaterSensor("sensor_1", 5000L, 50),
                new WaterSensor("sensor_2", 6000L, 60));
        // 创建表执行环境
        StreamTableEnvironment tableEnvironment = StreamTableEnvironment.create(env);

        // 创建表
        Table table = tableEnvironment.fromDataStream(streamSource);
        // TODO 动态查询 聚合函数
//        Table select = table
//                .where($("vc").isGreaterOrEqual(30))
//                .groupBy($("id"))
//                .aggregate($("vc").sum().as("vcSum"))
//                .select($("id"),  $("vcSum"));
                Table select = table
                .where($("vc").isGreaterOrEqual(30))
                .groupBy($("id"))
                .select($("id"),  $("vc").sum().as("vcSum" ));
        //TODO 表转换为流  撤回流  就可以用于聚合函数  每次将上一次的结果撤回 生成新结果
        DataStream<Tuple2<Boolean, Row>> reslut = tableEnvironment.toRetractStream(select, Row.class);
        //输出
        reslut.print();

        try {
            env.execute();
        } catch (Exception e) {
            e.printStackTrace();
        }


    }
}
